//此处写代码是没有代码提示的，请注意！
import { hvigor } from '@ohos/hvigor';
import { appTasks, OhosAppContext, OhosPluginId, OhosHapContext } from '@ohos/hvigor-ohos-plugin';
import fs from 'fs';
import path from 'path';

/**
 * 由于configEvaluated的生命周期早于node的初始化，所以无法根据工程上下文appContext.getBuildMode()来获取BuildMode的值;
 * 因此此处通过编译命令的命令行参数携带指定为buildMode,也可以在hvigor-config.json5里配置文件中的定义；通过获取properties配置中指定key值
 * 的value值。
 * 注意：记得确保同步切换编译模式，否则后续逻辑会报错！
 */
const currentBuildMode = hvigor.getParameter().getProperty('buildMode');
let isAddDependencies = false;
//configEvaluated只在hvigorconfig.ts里生效
hvigor.configEvaluated((hvigorConfig) => {
  //如果是debug编译模式就将debug_har加入到工程中参与编译
  if (currentBuildMode === 'debug') {
    hvigorConfig.includeNode('debug_har', './debug_har');
    isAddDependencies = true;
    console.log('The debug_har module has been added to the project.');
  }
});

hvigor.nodesEvaluated(() => {
  const rootNode = hvigor.getRootNode();
  //获取所有子节点,hvigor树的高度最多为2
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    const moduleName = hapContext?.getModuleName();
    const modulePath = hapContext?.getModulePath();
    if (moduleName === 'entry' && isAddDependencies) {
      const dependenciesInfo = hapContext.getDependenciesOpt();
      dependenciesInfo["debug_har"] = "../debug_har";
      hapContext.setDependenciesOpt(dependenciesInfo);
      console.log('The debug_har dependency has been added to the entry.');
      let indexEtsPath = modulePath + '/src/main/ets/pages/Index.ets';
      //要添加的内容
      const importStatement = "import { MainPage } from 'debug_har';\n";
      let fileContent = fs.readFileSync(indexEtsPath, 'utf-8');
      //在第一行插入import语句
      let newContent = importStatement + fileContent;
      //重新读取文件内容以获取新的INSERT_CODE_HERE位置
      fileContent = newContent;
      const insetPosition = fileContent.indexOf('//INSERT_CODE_HERE') + '//INSERT_CODE_HERE'.length;
      //要插入的内容
      const additionalCode = `
      MainPage()`;
      newContent = newContent.slice(0, insetPosition) + additionalCode + newContent.slice(insetPosition);
      fs.writeFileSync(indexEtsPath, newContent, 'utf-8');
      console.log('The code was successfully inserted into the index.ets of the entry module.');
    }
  });
});

//删除逻辑
function removeInsertedCode(filepath: string) {
  try {
    let fileContent = fs.readFileSync(filepath, 'utf-8');

    //先删除MainPage()代码块
    const mainPageRegex = /(\s*MainPage\(\))/gm;
    fileContent = fileContent.replace(mainPageRegex, '');
    //再删除import语句
    const importRegex = /^import\s+{.*}\s+from\s+['"]debug_har['"];\n/gm;
    fileContent = fileContent.replace(importRegex, '');
    fs.writeFileSync(filepath, fileContent, 'utf-8');
    console.log('The inserted code has been successfully deleted from the index.ets of the entry module.');
  } catch(error) {
    console.log('Failed to delete the inserted code from the index.ets of the entry module.Code:',error);
  }
}

// 编译完成后移除插入的代码
hvigor.buildFinished(buildResult => {
  if (buildResult.getError()) {
    console.log(buildResult.getError().stack);
  }

  const rootNode = hvigor.getRootNode();
  rootNode.subNodes((node: HvigorNode) => {
    const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    const moduleName = hapContext?.getModuleName();
    const modulePath = hapContext?.getModulePath();
    if (moduleName === 'entry' && isAddDependencies) {
      let indexEtsPath = modulePath + '/src/main/ets/pages/Index.ets';
      removeInsertedCode(indexEtsPath);
    }
  });
});
